// 通知
const { getNoticeList, getNoticeTotal, getNoticeInfo, removeNotice, updateNotice } = require('../../model/notice')
/**
 * 获取通知总数
 */

const noticeTotal = async (req, res) => {
    const output = {
        code: 200,
        msg: '操作成功'
    }
    const { id: uid } = req.loginInfo
    const map = { uid }
    const result = await getNoticeTotal(map)
    output.data = result
    res.send(output)
}

/**
 * 获取通知列表
*/
const noticeList = async (req, res) => {
    const output = {
        code: 200,
        msg: "操作成功"
    }
    // 获取登录用户id
    const { id: uid } = req.loginInfo
    const { page, size } = req
    const map = { uid }
    if (page && size) {
        map.page = page
        map.size = size
    }
    const result = await getNoticeList(map)
    if (result) {
        output.data = result
    }
    res.send(output)
}

/**
 *  通知详情 
 */
const noticeInfo = async (req, res) => {
    const output = {
        code: 200,
        msg: "操作成功"
    }
    const { id } = req.query
    if (!id) {
        output.code = 500
        output.msg = "参数错误：缺少参数id"
        return res.send(output)
    }
    const result = await getNoticeInfo(id)
    if (!result) {
        output.code = 500
        output.msg = "查询失败"
        return res.send(output)
    }
    res.send(output)
}


// removeNotice

/**
 *  删除通知 
 */
const noticeRemove = async (req, res) => {
    const output = {
        code: 200,
        msg: "操作成功"
    }
    const { id } = req.query
    if (!id) {
        output.code = 500
        output.msg = "参数错误：缺少参数id"
        return res.send(output)
    }
    const result = await removeNotice(id)
    if (!result) {
        output.code = 500
        output.msg = "删除失败"
        return res.send(output)
    }
    res.send(output)
}
/**
 *  更新通知状态: 
 *  传递一个通知id, 则是更新单条通知状态, 
 *  如果传递的是多个通知id组成字符串(如`1,2,3,4`),则执行批量更新
 */
const noticeUpdate = async (req, res) => {
    const output = {
        code: 200,
        msg: "操作成功"
    }
    let { id, status } = req.body
    if (!id) {
        output.code = 500
        output.msg = "参数错误：缺少参数id"
        return res.send(output)
    }
    // 更新条件
    const map = id.toString().includes(',') ? { id: id.split(',') } : id
    // 更新字段
    const fields = { status: status ? status : 2 }

    // 执行更新
    const result = await updateNotice(map, fields)
    output.data = result
    res.send(output)
}


/**
 * 更新所有通知的状态 
 */
const noticeUpdateAll = async (req, res) => {
    const output = {
        code: 200,
        msg: "操作成功"
    }
    // 获取参数
    const { status } = req.body
    // 获取登录账号id
    const { id: uid } = req.loginInfo
    // 更新字段
    const fields = { status: status ? status : 2 }
    // 批量更新通知状态
    const result = await updateNotice({ uid }, fields)
    output.data = result
    res.send(output)
}

module.exports = {
    noticeList,
    noticeTotal,
    noticeInfo,
    noticeRemove,
    noticeUpdate,
    noticeUpdateAll
}